package com.hcr.elecident;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.google.gson.Gson;

import java.net.URL;
import java.util.UUID;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    WebView webView;

    static final String[] PERMISSION = new String[]{
            //获取照相机权限
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityManager.getActivityManager().pushActivity(this);


        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //Android 6.0申请权限
            ActivityCompat.requestPermissions(this, PERMISSION, 1);
        }

        webView = (WebView) findViewById(R.id.myweb);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 增加localstore支持
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAppCacheMaxSize(1024*1024*8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);


        webView.addJavascriptInterface(this,"nativeMethod");

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView.loadUrl("file:///android_asset/1.html");
    }

//    @JavascriptInterface
//    public void camera1(String name,String num) {
//        Intent intent = new Intent(this,PreviewActivity.class);
//        intent.putExtra("name",name);
//        intent.putExtra("num",num);
//        System.out.println("name:"+name);
//        System.out.println("num:"+num);
//        startActivity(intent);
//    }

    @JavascriptInterface
    public void camera(String name,String num,String phone) {

        requestPermissions(99, Manifest.permission.CAMERA);
        initLib();


        Intent intent = new Intent(this,FaceDetectExpActivity.class);
        intent.putExtra("name",name);
        intent.putExtra("num",num);
        intent.putExtra("phone",phone);

        startActivity(intent);

//        startItemActivity(FaceDetectExpActivity.class);
    }

    @JavascriptInterface
    public void shareData(String phone) {

        // 判断是否有数据
        SharedPreferences pre = getSharedPreferences(WelcomeActivity.TEMP_DATA,MODE_PRIVATE);
        String info = pre.getString(phone,null);  //姓名
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+ info);
        if (info != null){
            String infos[] = info.split("@");
            final Intent it = new Intent(this, PageActivity.class);
            it.putExtra("name",infos[0]);
            it.putExtra("num",infos[1]);
            it.putExtra("fileName",infos[2]);
            startActivity(it);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


//    ############
    /**
     * 初始化SDK
     */
    public void initLib() {
        FaceSDKManager.getInstance().initialize(this, Config.licenseID, Config.licenseFileName);
    }

    public static void setFaceConfig() {
        FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();
        // SDK初始化已经设置完默认参数（推荐参数），您也根据实际需求进行数值调整
        config.setLivenessTypeList(ExampleApplication.livenessList);
        config.setLivenessRandom(ExampleApplication.isLivenessRandom);
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE);
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        config.setCheckFaceQuality(true);
        config.setFaceDecodeNumberOfThreads(2);

        FaceSDKManager.getInstance().setFaceConfig(config);
    }
    private void startItemActivity(Class itemClass) {
        setFaceConfig();
        startActivity(new Intent(this, itemClass));
    }

public void requestPermissions(int requestCode, String permission) {
    if (permission != null && permission.length() > 0) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                // 检查是否有权限
                int hasPer = checkSelfPermission(permission);
                if (hasPer != PackageManager.PERMISSION_GRANTED) {
                    // 是否应该显示权限请求
                    boolean isShould = shouldShowRequestPermissionRationale(permission);
                    requestPermissions(new String[]{permission}, requestCode);
                }
            } else {

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PackageManager.PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
        if (!flag) {
            requestPermissions(99, Manifest.permission.CAMERA);
        }
    }

//    sendHttp
    public void sendRequestWithOkHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    RequestBody body = new FormBody.Builder()
                            .add("","")
                            .build();
                    Request request = new Request.Builder()
                            .url(new URL(""))
                            .post(body)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static boolean isPase(String name,String idnumber,String image){
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("cmd","faceRecognition")
                    .add("name",name)
                    .add("idnumber",idnumber)
                    .add("image",image)
                    .add("imagetype","0")
                    .add("sendTime",Long.toString(System.currentTimeMillis()))
                    .add("terminalNo",UUID.randomUUID().toString())
                    .build();
            Request request = new Request.Builder()
                    .url(new URL(" https://182.50.124.210:9121/api"))
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            return isFacePase(parseJsonToInfoBean(responseData));
        } catch ( Exception e){
            e.printStackTrace();
        }
        return false;
    }
    public static InfoBean parseJsonToInfoBean(String str){
        InfoBean infoBean = new InfoBean();
        Gson gson = new Gson();
        infoBean = gson.fromJson(str,InfoBean.class);
        return infoBean;
    }

    public static boolean isFacePase(InfoBean infoBean){
        if (infoBean == null){
            return false;
        }
        if (infoBean.getResponseCode() == 100){
            if (infoBean.getResult().equals("1")){
                return true;
            } else {
                return false;
            }
        } else if (infoBean.getResponseCode() == 420){
            return false;
        } else {
            return false;
        }
    }
}

